<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\utils;

use app\index\model\Order;
use app\index\model\User;
use think\facade\Db;

class Agent
{
    public static $user;
    public static $config;

    /**
     *
     * @param $user
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function upgrade($user) : void{
        global $mid;
        self::$user = $user;
        $config = Db::name('configuration')
            ->where('type', 'agentExplain')
            ->where('mall_id',$mid)
            ->value('configuration');
        $agent = \app\index\model\Agent::where('user_id',$user['id'])->find();
        if(!empty($agent))return;
        $config = json_decode($config);
        self::$config = $config;
        $statistics = $config->become->condition->buyCommodity->statistics;
        if($statistics != 0)return;
        switch ($config->become->type) {
            case 1:
                self::commodity($config);
                break;
            case 2:
                self::money($config);
                break;
            case 3:
                self::number($config);
                break;
        }
    }

    /**
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private static function userToAgent() : void
    {
        $user = Db::name('user')->find(self::$user['id']);
        $config = self::$config;
        if ($config->isAudit == 1){
            $apply = Db::name('agent_apply')
                ->where('user_id',$user['id'])
                ->value('id');
            $data = self::getAgentApplyData($user);
            if (!empty($apply))
                Db::name('agent_apply')->where('id',$apply)->update($data);
            else
                Db::name('agent_apply')->insert($data);
        } else {
            $agent = Db::name('agent')
                ->where('user_id',$user['id'])
                ->find();
            $data = self::getAgentData($user);
            if (!empty($agent))
                Db::name('agent')->where('user_id', $user['id'])->update($data);
            else
                $agent_id = Db::name('agent')->insertGetId($data);
            $agent_id = empty($agent_id) ? $agent['id'] : $agent_id;
            Db::name('agent_apply')
                ->where('user_id',self::$user['id'])
                ->update(['status' => 1]);
            Db::name('user')
                ->where('id', self::$user['id'])
                ->update(['agent_id' => $agent_id]);
        }
    }

    /**
     * 购买商品升级分销商
     * @param $config
     */
    private static function commodity($config) : void
    {
        $commodity = $config->become->condition->buyCommodity->commodity;
        $count = Db::name('order')
            ->where('user_id',self::$user['id'])
            ->where('status', 'not in',[1,12])
            ->where('id', 'IN', function ($sql) use ($commodity) {
                $sql->name('order_commodity')
                    ->field('order_id')
                    ->where('commodity_id', 'IN', $commodity);
            })
            ->count();
        if($count > 0) self::userToAgent();
    }

    /**
     * 金额达到分销商标准
     * @param $config
     */
    private static function money($config) : void
    {
        $money = Db::name('order')
            ->where('user_id', self::$user['id'])
            ->where('status', 'not in',[1,12])
            ->sum('money');
        if (is_numeric($config->become->condition->explainTotal->statistics) && $config->become->condition->explainTotal->statistics==0){
            if ($money > $config->become->condition->explainTotal->explain)self::userToAgent();
        }
    }

    /**
     * 订单数量达到分销商标准
     * @param $config
     */
    private static function number($config) : void
    {
        $count = Db::name('order')
            ->where('user_id', self::$user['id'])
            ->where('status', 'not in',[1,12])
            ->count();
        if ($count > $config->become->condition->payOrder->orderCount)self::userToAgent();
    }

    /**
     *
     * @param $user
     * @return array
     */
    private static function getAgentData($user) : array{
        $data = [
            'user_id' => $user['id'],
            'mall_id' => $user['mall_id'],
            'name' => $user['nickname'],
            'mobile' => $user['mobile'],
            'pid' => $user['pid'],
            'apply_id' => 0,
            'status' => 1,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'delete_time' => null
        ];
        return $data;
    }

    /**
     *
     * @param $user
     * @return array
     */
    private static function getAgentApplyData($user) : array{
        $data = [
            'user_id' => $user['id'],
            'mall_id' => $user['mall_id'],
            'pid' => empty($user['pid']) ? 0 : $user['pid'],
            'name' => $user['nickname'],
            'mobile' => empty($user['mobile']) ? '' : $user['mobile'],
            'remark' => '满足条件自动申请',
            'status' => 0,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'delete_time' => null
        ];
        return $data;
    }


    /**
     *
     * @param $user
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function bindingPid($user) : void{
        $redis = new RedisUtil();
        $pid = $redis->get('pid-'.$user['id']);
        if (empty($pid))return;
        $order_count = Order::where('user_id',$user['id'])
            ->where('status','NOT IN',[1,12])
            ->count();
        if ($order_count > 0)return;
        $user = User::find($user['id']);
        if (empty($user))return;
        $user->save(['pid',$pid]);
        $agent = \app\index\model\Agent::where('user_id',$user->id)->find();
        if (!empty($agent))
            $agent->save(['pid' => $pid]);
    }
}